<template>
  <el-dialog v-model="visible" append-to-body :title="title" v-if="visible">
    <el-carousel
      trigger="click"
      height="70vh"
      :initialIndex="initialIndex"
      :autoplay="false"
      :pause-on-hover="false"
      @change="handleChange"
      style="overflow: hidden"
    >
      <el-carousel-item
        v-for="(item, index) in previewList"
        :key="item.id"
        style="width: 100%; overflow: hidden"
      >
        <div
          style="
            width: 100%;
            height: 100%;
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
          "
        >
          <img
            v-if="imageFormats.includes(item.fileExtension)"
            :src="item.url"
            :alt="item.name"
            width="100%"
            height="100%"
            style="object-fit: contain"
          />
          <video
            v-if="videoFormats.includes(item.fileExtension)"
            :src="item.url"
            style="width: 90%; height: 90%"
            controls
          ></video>
          <audio
            v-if="audioFormats.includes(item.fileExtension) && index === curIdx"
            :src="item.url"
            controls
            :key="item.id"
          ></audio>
          <div v-if="txtFormats.includes(item.fileExtension)">
            <div
              v-if="item.fileExtension === 'html'"
              v-html="item.fileStr || ''"
            ></div>
            <div v-else style="width: 100%; height: 100%; overflow-y: auto">
              <highlightjs
                :language="item.fileExtension"
                :code="item.fileStr || ''"
              ></highlightjs>
            </div>
          </div>

          <iframe
            v-if="
              pptFprmats.includes(item.fileExtension) ||
              wordFormats.includes(item.fileExtension) ||
              (excelFormats.includes(item.fileExtension) && index === curIdx)
            "
            width="99%"
            height="99%"
            :src="`http://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(
              item.url
            )}`"
            :key="item.id"
          ></iframe>
          <iframe
            v-if="pdfFormats.includes(item.fileExtension)"
            width="99%"
            height="99%"
            :key="item.id"
            :src="item.url"
          ></iframe>
        </div>
      </el-carousel-item>
    </el-carousel>
  </el-dialog>
</template>

<script setup>
import { apiDown } from '@/apis/file.js'
import { readFileTxtByUrl } from './utils'
const props = defineProps({
  needPreviewList: {
    type: Array,
    default: () => [],
  },
  belongModule: String,
  curPreviewIdx: Number,
})
const imageFormats = [
  'jpg', // JPEG 格式
  'jpeg', // JPEG 格式（另一种扩展名）
  'png', // PNG 格式
  'gif', // GIF 格式
  'webp', // WebP 格式
  'svg', // SVG 格式（矢量图）
  'bmp', // BMP 格式
  'ico', // ICO 格式（图标）
  'tiff', // TIFF 格式
  'tif', // TIFF 格式（另一种扩展名）
  'apng', // APNG 格式（动态 PNG）
]
const pptFprmats = ['ppt', 'pptx', 'pptm', 'pps', 'ppsx', 'pot', 'potx', 'potm']
const pdfFormats = ['pdf']
const wordFormats = ['doc', 'docx']
const excelFormats = ['xls', 'xlsx', 'xlsb', 'xlsm']
const videoFormats = ['mp4', 'mov', 'avi', 'ogg', 'webm']
const audioFormats = ['flac', 'aac', 'ogg', 'wav', 'mp3']
const txtFormats = ['txt', 'java', 'js', 'css', 'db', 'json', 'php', 'html']
const visible = defineModel(false)
const previewList = ref([])
const initialIndex = ref(0)
const loading = ref(false)

const title = computed(() => {
  if (previewList.value.length === 0) {
    return ''
  } else {
    return (
      previewList.value[curIdx.value]['showName'] ||
      previewList.value[curIdx.value]['name']
    )
  }
})
const curIdx = ref(0)
const handleChange = (val) => {
  curIdx.value = val
}
watch(
  () => visible.value,
  async (newV) => {
    if (newV) {
      // 每次打开弹窗清空之前加载的预览数据
      previewList.value = []
      // 拿到需要加载预览数据的id集合
      let ids = props.needPreviewList.map((item) => item.id).join(',')
      // 获取预览文件的地址
      let resList = await apiDown(props.belongModule, ids, loading)
      for (const item of resList) {
        if (txtFormats.includes(item.fileExtension)) {
          let str = await readFileTxtByUrl(item.url)
          item.fileStr = str
        }
      }
      let newList = []
      // 注意接口返回的文件顺序并不是我们传入id的顺序，需要手动重新排序
      props.needPreviewList.forEach((item) => {
        let idx = resList.findIndex((itm) => itm.id === item.id)
        if (idx > -1) {
          newList.push(resList[idx])
        }
      })
      // 赋值预览数据
      previewList.value = newList
      // 设置从第几个轮播开始展示
      initialIndex.value = props.curPreviewIdx
      curIdx.value = props.curPreviewIdx
    }
  }
)
</script>

<style lang="scss" scoped></style>
